﻿using System.Diagnostics;

namespace excel2bean
{
    public class Program
    {
        static void Main(string[] args)
        {
            DateTime now = DateTime.Now;

            Exporter exporter = new Exporter(args[0], args[1], args[2], args[3]);
            Task mainTask = Task.Run(exporter.Export);

            int line = 1;   //日志从第二行开打 第一行留给进度条

            //循环读取日志
            while (!mainTask.IsCompleted)
            {
                PullOutputs(ref line, exporter);

                //每100ms拉一次
                Task.Delay(100).Wait();
            }

            if (mainTask.IsFaulted)
            {
                //异步操作失败
                Debug.Assert(mainTask.Exception != null);

                Console.WriteLine(mainTask.Exception.ToString());
            }
            else
            {
                //成功结束 拉一次输出
                PullOutputs(ref line, exporter);
            }

            Console.WriteLine($"操作结束，总耗时{DateTime.Now - now}");
        }

        static void PullOutputs(ref int line, Exporter exporter)
        {
            Console.SetCursorPosition(0, 0);
            if (string.IsNullOrEmpty(exporter.stage))
            {
                Console.WriteLine("执行中");
            }
            else
            {
                // 打印进度条
                PrintProgressBar(exporter.stage, exporter.value, exporter.total);
            }

            Console.SetCursorPosition(0, line);

            while (exporter.outputs.TryDequeue(out string? output))
            {
                Console.WriteLine(output);
            }

            line = Console.CursorTop;
        }

        static void PrintProgressBar(string stage, int value, int total)
        {
            double progress = (double)value / total;
            int barLength = 50;
            int pos = (int)(barLength * progress);

            Console.Write($"{stage}[");
            for (int i = 0; i < barLength; i++)
            {
                if (i < pos)
                {
                    Console.Write("=");
                }
                else if (i == pos)
                {
                    Console.Write(">");
                }
                else
                {
                    Console.Write(" ");
                }
            }
            Console.WriteLine("] {0:P0}     ", progress);
        }
    }
}